<template>
  <div class="server-main">
    <div class="server-table">
      <div class="table-title">
        <span class="table-title-text">逻辑模型管理</span>
      </div>
      <div class="item-list-warpper">
        <el-table :data="selectedModelList" class="km-table">
          <el-table-column
            prop="logicalModelId"
            label="ID"
            width="50"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="modelCode"
            label="模型编码"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="modelName"
            label="模型名称"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="description"
            label="模型说明"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="themeName"
            label="所属主题"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="version"
            label="版本"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="modelStatus"
            label="状态"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <i
                class="little-circle-yellow"
                v-if="scope.row.modelStatus === 0"
              ></i>
              <span v-if="scope.row.modelStatus === 0">编辑中</span>
              <i
                class="little-circle-green"
                v-if="scope.row.modelStatus === 1"
              ></i>
              <span v-if="scope.row.modelStatus === 1">已发布</span>
              <i
                class="little-circle-red"
                v-if="scope.row.modelStatus === 2"
              ></i>
              <span v-if="scope.row.modelStatus === 2">已停用</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="250">
            <template slot-scope="scope">
              <el-link
                v-if="scope.row.modelStatus === 0"
                :underline="false"
                type="primary"
                class="ontology-edit"
                @click.native.prevent="openEditModel(scope.row)"
                >编辑</el-link
              >
              <el-link
                v-if="scope.row.modelStatus === 0"
                :underline="false"
                type="primary"
                class="ontology-edit"
                @click.native.prevent="handlePublish(scope.row)"
                >发布</el-link
              >
              <el-link
                v-if="scope.row.modelStatus === 2"
                :underline="false"
                type="primary"
                class="ontology-edit"
                @click.native.prevent="handlePublish(scope.row)"
                >启用</el-link
              >
              <el-link
                v-if="scope.row.modelStatus === 0"
                :underline="false"
                type="primary"
                class="ontology-edit"
                @click.native.prevent="modelDelete(scope.row)"
                >删除</el-link
              >
              <!-- <el-link
                v-if="!isEdit"
                :underline="false"
                type="primary"
                class="ontology-edit"
                @click.native.prevent="applyRecord(scope.row.modelId)"
              >修订</el-link>  -->
              <el-link
                v-if="scope.row.modelStatus === 1"
                :underline="false"
                type="primary"
                class="ontology-edit"
                @click.native.prevent="handleAbolish(scope.row)"
                >停用</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="button-group">
        <div>
          <el-button
            type="primary"
            size="small"
            @click="handleAddItem"
            :disabled="!isEdit"
            >新建</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="savePropsList"
            :disabled="!isEdit"
            >保存</el-button
          >
        </div>
      </div>
      <div>
        <el-form ref="tabelListFix" :model="this">
          <el-table
            :data="tableList"
            class="km-table"
            style="width: 100%; height: 80%"
            highlight-current-row
            :height="tableHeight"
            ref="propsTable"
          >
            <el-table-column
              label="属性中文名"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="`tableList[${scope.$index}].columnName`"
                  :rules="{
                    required: true,
                    message: '请输入中文名',
                    trigger: 'change',
                  }"
                >
                  <el-input
                    v-if="scope.row.edit != 0"
                    size="small"
                    v-model="scope.row.columnName"
                    placeholder="请输入内容"
                    @change="
                      handleCurrentChange(
                        scope.$index,
                        'columnName',
                        scope.row.columnName
                      )
                    "
                  ></el-input>
                  <span v-if="scope.row.edit == 0">{{
                    scope.row.columnName
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              label="属性英文名"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="`tableList[${scope.$index}].columnField`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入英文名',
                      trigger: 'change',
                    },
                    { validator: isEnglish, trigger: 'change' },
                  ]"
                >
                  <el-input
                    v-if="scope.row.edit != 0"
                    size="small"
                    v-model="scope.row.columnField"
                    placeholder="请输入内容"
                    @change="
                      handleCurrentChange(
                        scope.$index,
                        'columnField',
                        scope.row.columnField
                      )
                    "
                  ></el-input>
                  <span v-if="scope.row.edit == 0">{{
                    scope.row.columnField
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="数据类型"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="`tableList[${scope.$index}].columnType`"
                  :rules="{
                    required: true,
                    message: '请选择数据类型',
                    trigger: 'change',
                  }"
                >
                  <el-select
                    v-if="scope.row.edit != 0"
                    v-model="scope.row.columnType"
                    placeholder="请选择"
                    @change="
                      handleCurrentChange(
                        scope.$index,
                        'columnType',
                        scope.row.columnType
                      )
                    "
                  >
                    <el-option
                      v-for="item in typesOptions"
                      :key="item.value"
                      :label="item.key"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <span v-if="scope.row.edit == 0">{{
                    scope.row.columnType
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="长度"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="`tableList[${scope.$index}].columnLength`"
                  :rules="{
                    required: true,
                    message: '请输入长度',
                    trigger: 'change',
                  }"
                >
                  <el-input
                    v-if="scope.row.edit != 0"
                    size="small"
                    v-model="scope.row.columnLength"
                    placeholder="请输入内容"
                    @change="
                      handleCurrentChange(
                        scope.$index,
                        'columnLength',
                        scope.row.columnLength
                      )
                    "
                  ></el-input>
                  <span v-if="scope.row.edit == 0">{{
                    scope.row.columnLength
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="精度"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="`tableList[${scope.$index}].columnPrecision`"
                  :rules="{
                    required: true,
                    message: '请输入精度',
                    trigger: 'change',
                  }"
                >
                  <el-input
                    v-if="scope.row.edit != 0"
                    size="small"
                    v-model="scope.row.columnPrecision"
                    placeholder="请输入内容"
                    @change="
                      handleCurrentChange(
                        scope.$index,
                        'columnPrecision',
                        scope.row.columnPrecision
                      )
                    "
                  ></el-input>
                  <span v-if="scope.row.edit == 0">{{
                    scope.row.columnPrecision
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="注释"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-input
                  v-if="scope.row.edit != 0"
                  size="small"
                  v-model="scope.row.columnRemark"
                  placeholder="请输入内容"
                  @change="
                    handleCurrentChange(
                      scope.$index,
                      'columnRemark',
                      scope.row.columnRemark
                    )
                  "
                ></el-input>
                <span v-if="scope.row.edit == 0">{{
                  scope.row.columnRemark
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="排序"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span>{{ scope.row.orderNum }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="唯一标识"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="`tableList[${scope.$index}].onlyIdentification`"
                  :rules="{
                    required: true,
                    message: '请选择是否唯一标识',
                    trigger: 'change',
                  }"
                >
                  <el-select
                    v-if="scope.row.edit != 0"
                    v-model="scope.row.onlyIdentification"
                    placeholder="请选择"
                    @change="
                      handleCurrentChange(
                        scope.$index,
                        'onlyIdentification',
                        scope.row.onlyIdentification
                      )
                    "
                  >
                    <el-option
                      v-for="item in ifUUID"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <span v-if="scope.row.edit == 0">{{
                    scope.row.onlyIdentification === 0 ? "否" : "是"
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" v-if="isEdit">
              <template slot-scope="scope">
                <el-link
                  :underline="false"
                  type="primary"
                  class="ontology-edit"
                  @click.native.prevent="handleEdit(scope.$index, scope.row)"
                  >{{ scope.row.edit == 0 ? "编辑" : "取消" }}</el-link
                >
                <!-- <el-link
              v-if='scope.row.edit===1'
                :underline="false"
                type="primary"
                class="ontology-edit"
                @click.native.prevent="cancelProperty(scope.$index, scope.row)"
              >{{scope.row.edit==0?'编辑':'取消'}}</el-link> -->
                <el-link
                  :underline="false"
                  type="primary"
                  class="ontology-edit"
                  @click.native.prevent="handleDelete(scope.$index, scope.row)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <el-dialog
          title="编辑模型"
          :visible.sync="dialogFormVisible"
          @close="afterDialogClose"
        >
          <el-form
            :model="modelParams"
            :rules="rules"
            ref="dialogForm"
            label-position="right"
            label-width="120px"
          >
            <el-form-item
              label="模型编码:"
              prop="modelCode"
              class="dialog-inline"
            >
              <el-input
                v-model.trim="modelParams.modelCode"
                :disabled="true"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="模型名称:"
              prop="modelName"
              class="dialog-inline"
            >
              <el-input v-model.trim="modelParams.modelName"></el-input>
            </el-form-item>
            <el-form-item
              label="模型说明:"
              prop="description"
              class="dialog-inline"
            >
              <el-input
                type="textarea"
                v-model.trim="modelParams.description"
                :autosize="textSizeConfig"
              >
              </el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="resetDialogForm">取 消</el-button>
            <el-button
              type="primary"
              @click="submitDialogForm"
              :loading="loading"
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  components: {},
  data() {
    return {
      // 表格高度
      tableHeight: "56vh",
      // 判断状态为编辑中或已发布
      // 属性列表,
      selectedModelList: [], //模型列表
      tableList: [],
      total: 0, // 数据总条数
      typesOptions: [], //数据类型列表
      modelId: -1, //逻辑模型id
      modelParams: {
        //编辑模型模板
        logicalModelId: 0,
        modelCode: "", // 模型编码
        modelName: "", // 模型名称
        modelDescription: "", // 模型说明
        description: "",
      },
      dialogType: "edit",
      dialogFormVisible: false, //创建、编辑弹窗默认状态
      rules: {
        //弹窗表单项规则
        modelCode: [
          {
            required: true,
            message: "请输入模型编码",
            trigger: "blur",
          },
        ],
        modelName: [
          {
            required: true,
            message: "请输入模型名称",
            trigger: "blur",
          },
        ],
        description: [
          {
            required: false,
            message: "请输入模型描述",
            trigger: "blur",
          },
        ],
        selectedType: "",
      },
      textSizeConfig: {
        //texterea设置4-10行
        minRows: 4,
        maxRows: 10,
      },
      loading: false,
      ifUUID: [
        {
          //是否唯一标识
          value: 1,
          label: "是",
        },
        {
          value: 0,
          label: "否",
        },
      ],
    };
  },
  computed: {
    ...mapState({
      selectedData: (state) => state.modelDesign.selectData,
      isEdit: function (state) {
        let status = state.modelDesign.selectData.modelStatus;
        if (status === 0) return true;
        if (status === 1) return false;
      },
    }),
  },
  created() {
    this.getPropsData(this.selectedData);
    this.getDataTypeList();
  },
  methods: {
    //属性英文校验
    isEnglish(rule, value, cb) {
      const rex = /^[a-zA-Z][a-zA-Z0-9_]+$/;
      if (!rex.test(value)) {
        cb(
          new Error("字段格式必须是以字母开头,至少两个字符，且只能写_特殊字符")
        );
      }
      cb();
    },
    //获取属性列表
    getPropsData(item) {
      let id = item.logicalModelId || null;
      this.$axios
        .post(
          `${this.$api.modelDesign.logicModel.getModelPropertyList}?logicalModelId=${id}`
        )
        .then((res) => {
          let data = res.data.data;
          this.selectedModelList = data.logicalModelList.slice(0, 1);
          this.modelId = this.selectedModelList[0].logicalModelId;
          let newArr = [];
          data.fieldList.map((item, index) => {
            //设置属性编辑状态，默认非
            newArr.push(Object.assign(item, { edit: 0 }));
          });
          this.tableList = newArr;
          this.total = res.data.data.total;
        })
        .catch((err) => {
          this.$message.error(err.data.message);
        });
    },
    //行内编辑相关方法
    handleCurrentChange(index, key, val) {
      this.$set(this.tableList[index], key, val);
    },

    handleEdit(index, row) {
      // 表格数据前端处理，需要把旧值存起来，用户点击编辑之后修改了原来的数据，但是又点了取消的情况，还需要获取到原来的值
      if (row.edit == 0) {
        sessionStorage.setItem(
          `oldPropertValue${row.logicalModelFieldId}`,
          JSON.stringify(row)
        );
        this.$set(this.tableList[index], "edit", 1);
      } else {
        this.cancelProperty(row, index);
      }
    },
    // 获取数据类型列表
    getDataTypeList() {
      let params = { code: "column_type", source: 2 };
      this.$axios
        .post(this.$api.modelDesign.logicModel.dataTypeList, params)
        .then((res) => {
          let data = res.data.data;
          this.typesOptions = data;
        })
        .catch((error) => {
          this.loading = false;
          this.$message.error(error.data.message);
        });
    },
    // 取消属性编辑
    cancelProperty(row, index) {
      console.log(
        sessionStorage.getItem(`oldPropertValue${row.logicalModelFieldId}`) ==
          null
      );
      if (
        sessionStorage.getItem(`oldPropertValue${row.logicalModelFieldId}`) !=
        null
      ) {
        let data = JSON.parse(
          sessionStorage.getItem(`oldPropertValue${row.logicalModelFieldId}`)
        );
        data["edit"] = 0;
        this.$set(
          this.tableList,
          index,
          JSON.parse(
            sessionStorage.getItem(`oldPropertValue${row.logicalModelFieldId}`)
          )
        );
      } else {
        this.tableList.pop();
      }
    },
    // 保存属性列表
    savePropsList() {
      let flag = false;
      this.$refs.tabelListFix.validate((valid) => {
        flag = valid;
      });
      if (!flag) {
        return;
      }
      let params = {
        logicalModelId: this.modelId,
        logicalModelFieldList: this.tableList,
      };
      this.loading = true;
      this.$axios
        .post(this.$api.modelDesign.physicModel.saveModelProps, params)
        .then((res) => {
          this.loading = false;
          this.tableList.map((item) => (item.edit = 0));
          this.$message({ message: "操作成功!", type: "success" });
          this.$nextTick(() => {
            this.getPropsData(this.selectedData);
          });
        })
        .catch((error) => {
          this.loading = false;
          this.$message.error(error.data.message);
        });
    },
    // 添加一行属性
    handleAddItem() {
      // 向数组中添加一条数据
      let item = {
        logicalModelFieldId: null, //列表项唯一标识
        columnName: "", //属性中文名
        columnField: "", //属性英文名
        columnType: "", //属性类型(下拉可选）
        columnLength: 0, //长度
        columnPrecision: 0, //精度
        columnRemark: "", //注释
        orderNum: this.tableList.length + 1, //排序
        onlyIdentification: 0,
        onlyIdentificationValue: "否", //唯一标识（默认否）
        edit: 1,
      };
      this.tableList.push(item);
      //滚动到最后一行
      this.$nextTick(function () {
        //此处必须使用nextTick函数,使页面渲染完后再执行
        this.$refs.propsTable.bodyWrapper.scrollTop =
          this.$refs.propsTable.bodyWrapper.scrollHeight;
      });
    },
    //删除属性元素
    handleDelete(index, row) {
      this.tableList.splice(index, 1);
      this.$message({ message: "删除成功!", type: "success" });
    },
    // 打开编辑模型模态框
    openEditModel(row) {
      this.dialogType = "edit";
      this.modelParams.logicalModelId = row.logicalModelId;
      this.modelParams.modelCode = row.modelCode;
      this.modelParams.modelName = row.modelName;
      this.modelParams.description = row.description;
      this.dialogFormVisible = true;
    },
    // 确定
    submitDialogForm() {
      let _this = this;
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          this.editLogicModel();
          this.dialogFormVisible = false;
        } else {
          return false;
        }
      });
    },
    // 编辑模型
    editLogicModel() {
      let params = this.modelParams;
      this.loading = true;
      this.$axios
        .post(this.$api.modelDesign.logicModel.editLogicModel, params)
        .then((res) => {
          this.loading = false;
          this.$message({ message: "编辑成功!", type: "success" });
          this.$store.commit("modelDesign/save_selectData", {
            ...this.selectedData,
            ...this.modelParams,
          });
          this.$nextTick(() => {
            this.getPropsData(this.selectedData);
          });
        })
        .catch((error) => {
          this.loading = false;
          this.$message.error(error.data.message);
        });
    },
    //发布/启用模型
    handlePublish(row) {
      this.$confirm("是否确认发布该版本模型？")
        .then(() => {
          let params = { logicalModelId: row.logicalModelId, modelStatus: 1 };
          this.loading = true;
          this.$axios
            .post(this.$api.modelDesign.logicModel.publishModel, params)
            .then((res) => {
              this.loading = false;
              this.$store.commit("modelDesign/save_selectData", {
                ...this.selectedData,
                ...{ modelStatus: 1 },
              });
              this.$message({ message: "发布成功!", type: "success" });
              this.$nextTick(() => {
                this.getPropsData(this.selectedData);
              });
            })
            .catch((error) => {
              this.loading = false;
              this.$message.error(error.data.message);
            });
        })
        .catch(() => {});
    },
    //废止模型
    handleAbolish(row) {
      this.$confirm("是否确认废止该版本模型？")
        .then(() => {
          let params = { logicalModelId: row.logicalModelId, modelStatus: 2 };
          this.loading = true;
          this.$axios
            .post(this.$api.modelDesign.logicModel.publishModel, params)
            .then((res) => {
              this.loading = false;
              this.$store.commit("modelDesign/save_selectData", {
                ...this.selectedData,
                ...{ status: 2 },
              });
              this.$message({ message: "操作成功!", type: "success" });
              this.$nextTick(() => {
                this.getPropsData(this.selectedData);
              });
            })
            .catch((error) => {
              this.loading = false;
              this.$message.error(error.data.message);
            });
        })
        .catch(() => {});
    },
    //删除模型--当前版本
    modelDelete(row) {
      this.$confirm("是否确认删除该版本模型？ 删除后将无法恢复，请谨慎操作!")
        .then(() => {
          this.loading = true;
          this.$axios
            .post(
              `${this.$api.modelDesign.logicModel.deleteModelVersion}?logicalModelId=${row.logicalModelId}`
            )
            .then((res) => {
              this.loading = false;
              this.$message({ message: "删除成功!", type: "success" });
              this.$router.push(`/dataReceive/modelDesign/logicModel`);
            })
            .catch((error) => {
              this.loading = false;
              this.$message.error(error.data.message);
            });
        })
        .catch(() => {});
    },
    // 取消
    resetDialogForm() {
      this.dialogFormVisible = false;
    },
    // 模态框关闭后
    afterDialogClose() {
      this.$refs.dialogForm && this.$refs.dialogForm.resetFields();
    },
  },
};
</script>
<style lang="scss" scoped>
.server-main {
  position: relative;
  .button-group {
    display: flex;
    justify-content: flex-end;
    padding: 16px 0 10px 0;
  }
  .server-table {
    margin-top: 16px;
    padding: 16px 32px 64px;
    border-radius: 4px;
    background: #ffffff;
    .item-list-warpper {
      padding-bottom: 24px;
      border-bottom: 1px solid #dcdce6;
    }
    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
      }

      margin-bottom: 10px;
    }

    .little-circle-green {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #55c898;
      position: relative;
      right: 4px;
      top: -2px;
    }

    .little-circle-red {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #ee5564;
      position: relative;
      right: 6px;
      top: -2px;
    }

    .little-circle-yellow {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #dba839;
      position: relative;
      right: 6px;
      top: -2px;
    }

    .page-wrapper {
      margin-top: 28px;
      display: flex;
      justify-content: flex-end;
      color: rgba(0, 0, 0, 0.65);

      .data-counter {
        font-weight: 400;
        line-height: 32px;
        margin-right: 24px;
      }

      /deep/ .btn-prev,
      /deep/ .btn-next {
        margin: 0 4px;
        min-width: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        padding: 0;
      }

      /deep/ .el-pager .number {
        min-width: 28px;
        height: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin: 0 4px;
        cursor: pointer;
      }
    }
  }
  .ontology-edit {
    padding: 0 10px;

    & + .ontology-edit {
      border-left: 1px solid #dddddd;
    }
  }
  ::v-deep .el-dialog {
    width: 500px;
    border-radius: 5px;
  }
  ::v-deep .el-form-item {
    margin-bottom: 0px;
  }
  // ::v-deep .el-table .cell {
  //   overflow: revert;
  // }
  ::v-deep .el-form-item__error {
    white-space: pre-line;
    padding-top: 1px;
    // z-index: 10000;
    overflow: hidden;
    text-align: left;
    width: 130%;
    top: 60%;
    -webkit-transform-origin-x: 0;
    transform: scale(0.8);
  }
  ::v-deep .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
  ::v-deep .el-textarea__inner {
    font-family: inherit;
  }
}
</style>
